<template>
    按钮
  <div class="modal-button" @click="handleOpen">
    <slot name="button">
      <button>open</button>
    </slot>
  </div>

  <teleport to="body">
    <div v-if="modalOpen" class="modal">
      <div>
        <slot name="content"/>
        <button @click="handleClose">
          close
        </button>
      </div>
    </div>
  </teleport>
</template>
<script>
import { ref, watch } from 'vue'
export default {
  name: 'Modal',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  emits: ['close', 'open'],
  setup(props, { emit }) {
    const { modalOpen, handleClose, handleOpen } = useModal(props, emit)
    return {
      modalOpen,
      handleOpen,
      handleClose
    }
  }
}

function useModal(props, emit) {
  const modalOpen = ref(props.show)

  watch(() => props.show, (show) => {
    show ? handleOpen() : handleClose()
  })

  function handleClose() {
    modalOpen.value = false
    emit('close')
  }

  function handleOpen() {
    modalOpen.value = true
    emit('open')
  }

  return {
    modalOpen,
    handleOpen,
    handleClose
  }
}
</script>
